package com.xatl.simulated.client;

import com.xatl.simulated.constant.MqttPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Slf4j
@Component
public class MqttPublishClient {

    @Autowired
    private MqttPropertiesUtils MqttProperties;

    @Autowired
    private MyMqttClient myMqttClient;

    private static MqttClient mqttClient = null;

    @PostConstruct
    public void init(){
        mqttClient = myMqttClient.init(MqttProperties.getPublish());
    }

    public static void publish(String topic, int qos, String content) {
        try {
            MqttMessage mqttMessage = new MqttMessage(content.getBytes());
            mqttMessage.setQos(qos);

//            MqttPublishClient.mqttClient.setCallback(new MqttReceiveCallback(mqttClient, topic, qos));
            MqttPublishClient.mqttClient.publish(topic, mqttMessage);
        } catch (MqttException me) {
            log.error("reason " + me.getReasonCode());
            log.error("msg " + me.getMessage());
            log.error("loc " + me.getLocalizedMessage());
            log.error("cause " + me.getCause());
            log.error("excep " + me);
        }
    }

    public void disconnect() {
        try {
            MqttPublishClient.mqttClient.disconnect();
            MqttPublishClient.mqttClient.close();
        } catch (MqttException me) {
            log.error("reason " + me.getReasonCode());
            log.error("msg " + me.getMessage());
            log.error("loc " + me.getLocalizedMessage());
            log.error("cause " + me.getCause());
            log.error("excep " + me);
        }
    }

}
